import dotenv from 'dotenv';
import readline from 'readline';
import fetch, { Response } from 'node-fetch';
import { marked } from 'marked'; // <-- 新增: 导入 marked
import TerminalRenderer from 'marked-terminal'; // <-- 新增: 导入终端渲染器

// --- 新增: 配置 marked 使用终端渲染器 ---
marked.setOptions({
  renderer: new TerminalRenderer()
});
// -----------------------------------------

// 加载 .env 文件
dotenv.config({ quiet: true });

const apiKey: string | undefined = process.env.API_KEY;
const baseUrl: string = process.env.BASE_URL || 'https://api.openai.com/v1/chat/completions';
const model = 'gemini-2.5-flash';

// ... [接口定义等其他代码保持不变] ...
interface ChatMessage {
  role: 'user' | 'assistant';
  content: string;
}
interface ApiResponseChunk {
  choices?: {
    delta?: { content?: string; };
    message?: ChatMessage;
  }[];
  error?: { message: string; };
}
if (!apiKey) {
  console.error('错误：.env 文件中未定义 API_KEY。');
  process.exit(1);
}
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
// ------------------------------------

async function main() {
  console.log('聊天机器人已准备就绪。输入 "exit" 即可退出。🤖');
  const conversationHistory: ChatMessage[] = [];

  const chat = async () => {
    rl.question('你: ', async (userInput: string) => {
      if (userInput.toLowerCase() === 'exit') {
        rl.close();
        return;
      }
      conversationHistory.push({ role: 'user', content: userInput });

      try {
        const response: Response = await fetch(baseUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${apiKey}`,
          },
          body: JSON.stringify({
            model: model,
            messages: conversationHistory,
            stream: true,
          }),
        });

        if (!response.body) {
          throw new Error('响应体不存在');
        }

        process.stdout.write('机器人: ');
        let fullBotMessage = '';

        for await (const chunk of response.body) {
          const chunkStr = chunk.toString();
          const lines = chunkStr.split('\n\n').filter(line => line.trim());

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const jsonData = line.substring(6);
              if (jsonData === '[DONE]') break;
              try {
                const parsedChunk: ApiResponseChunk = JSON.parse(jsonData);
                const delta = parsedChunk.choices?.[0]?.delta?.content;
                if (delta) {
                  process.stdout.write(delta);
                  fullBotMessage += delta;
                }
              } catch (parseError) { /* 忽略解析错误 */ }
            }
          }
        }

        // --- 关键改动: 流结束后，用 Markdown 格式化并重新打印 ---
        // 1. 使用 '\r' 将光标移动到行首
        process.stdout.write('\r');
        // 2. 清除从光标到行尾的所有内容
        process.stdout.clearLine(1);
        // 3. 打印带前缀和 Markdown 格式的完整消息
        console.log(`机器人: ${marked(fullBotMessage.trim())}`);
        // ----------------------------------------------------

        if (fullBotMessage) {
          conversationHistory.push({ role: 'assistant', content: fullBotMessage });
        }

      } catch (error) {
        console.error('\n请求 API 时出错:', error instanceof Error ? error.message : '发生未知错误。');
        conversationHistory.pop();
      }
      chat();
    });
  };
  chat();
}

main();